package com.aube.mis.helper;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aube.constant.ErrorCodeConstant;
import com.aube.mis.enums.ResponseCode;
import com.aube.mis.exception.MisException;
import com.aube.support.ResultCode;

@Aspect
@Component
public class ServerAspect {

	private static Logger log = LoggerFactory.getLogger(ServerAspect.class);

	/**
	 * 统一打印server请求的参数和返回
	 * 
	 * @param joinPoint
	 * @param rvt
	 */
	@AfterReturning(returning = "rvt", pointcut = "execution(* com.aube.api..*(..)) || execution(* com.aube.apiv2..*(..))")
	public void afterReturning(JoinPoint joinPoint, Object rvt) {
		Object[] args = joinPoint.getArgs();
		log.info("method: {}, parameter: {}, response: {}",
				new Object[] { joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), JSON.toJSONString(args), JSON.toJSONString(rvt) });
		if (rvt instanceof ResultCode) {
			ResultCode<?> result = (ResultCode<?>) rvt;
			if (!ErrorCodeConstant.Common.CODE_SUCCESS.equals(result.getErrcode())) {
				ResponseCode responseCode = ResponseCode.getEnumByCode(result.getErrcode());
				if (responseCode != null) {
					throw new MisException(responseCode);
				} else {
					throw new MisException(result.getErrcode(), result.getErrmsg());
				}
			}
		}
	}
}
